#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:计算最近4次每次的订烟额环比值
code:OrderAmount_FallingRate_Check_2
tableName:
columnName:
groups:准入>烟商
dependencies:BTM
type:常用指标
dataSourceType:在线指标
description:
eof'''

'''
取最近4次订烟 订烟额 计算4次每次的订烟额环比值
若没有4次订烟额 直接返回 -999999
若4次中有一次为空 则返回-999999
有分母为0 返回 -999999
返回list [] 3个比率 , 
'''

import sys
import pandas as pd
import datetime
import numpy as np

reload(sys)
sys.setdefaultencoding('utf-8')


def Rule53_OrderAmount_FallingRate_Check_2():
    null_type_list = ['', None, 'null', 'Null', '/']
    indent = {}
    indent_money = []
    ratio = []
    try:
        BTM_ = BTM['data']
        if Formate(BTM_.get('bbd_dotime')) is not None:
            ApplTime = datetime.datetime.strptime(Formate(BTM_['bbd_dotime']), '%Y%m%d')
            last_year_list = [(ApplTime - pd.tseries.offsets.DateOffset(days=i * 30)).strftime('%Y%m%d') \
                              for i in [12, 0]]
        else:
            last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=i * 30)).strftime('%Y%m%d') \
                              for i in [12, 0]]
    except:
        return -999999
    try:
        if BTM_.has_key('indent') and BTM_['indent'] not in null_type_list \
                and len(BTM_['indent']) >= 4:
            for i in BTM_['indent']:
                if i.has_key('indentDate') and i['indentDate'] not in null_type_list \
                    and isfloat(i['indentMoney']) is not None and isfloat(i['indentMoney']) > 0 \
                    and Formate(i['indentDate']) is not None \
                    and Formate(i['indentDate']) > last_year_list[0] and Formate(i['indentDate']) <= last_year_list[1]:
                    if indent.has_key(Formate(i['indentDate'])):
                        key = Formate(i['indentDate'])
                        indent[key].append(isfloat(i['indentMoney']))
                    else:
                        #isfloat()函数返回金额 和 None 当indentMoney非正常时，为None
                        indent.update({Formate(i['indentDate']):[isfloat(i['indentMoney'])]})
            #按时间降序
            keys = sorted(indent,reverse=True)
            #仅取最近四次订单

            for k in keys[0:4]:
                if None  in indent[k]:
                    return -999999
                else:
                    indent_money.append(sum(indent[k]))

            for j in xrange(3):
                #整数化，使得结果正常
                ratio.append(((float(indent_money[j])/float(indent_money[j+1]))*10 -10)/float(10))
            #直接返回三个比率
            return max(ratio)
        else:
            return -999999
    except:
        return -999999

#考虑，返回：金额 否则为None
def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            return float(x)
        else:
            return None
    except:
        return None

#统一时间格式为'20180528'-> '%Y%m%d'
def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

    
result = Rule53_OrderAmount_FallingRate_Check_2()